import { ResponseCode } from '@/utils/ResponseCode';
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Observable } from 'rxjs';

@Injectable()
export class SessionGuard implements CanActivate {
  constructor(private reflector: Reflector) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    // 是否需要登入才能访问
    const needLogin = this.reflector.get<false | undefined>(
      'needLogin',
      context.getHandler(),
    );
    // 默认是undefined，如果传入false，那么不阻拦
    if (needLogin === false) {
      return true;
    }
    const request = context.switchToHttp().getRequest();

    const isLogin = Boolean(request.session.username);
    // 没有登入成功表名用户需要重新返回登入页面
    if (!isLogin) {
      throw new HttpException(
        {
          message: '用户登入信息失效',
          code: ResponseCode.Fail,
          data: null,
        },
        // 401表示登入状态有误
        HttpStatus.UNAUTHORIZED,
      );
    }
    return isLogin;
  }
}
